#include "FSMFactory.hpp"
#include <iostream>
#include <cstdlib>
#include <map>
#include <set>

FSMFactory::FSMFactory(const std::string& pattern, Edge* emptyEdge)
:pattern_(pattern),automaton_(emptyEdge)
{	
	tokenizer_ = new Tokenizer(pattern);
	buildAutomaton();
}

Edge* FSMFactory::GetEmptyEdge() { return new Edge(); }

void FSMFactory::buildAutomaton()
{
	
}

void FSMFactory::DumpAutomaton()
{
	std::fstream file("dump.dat", std::fstream::out);
	file << "digraph dump {\n";
	printAndGo(automaton_, file);
	file << "}\n";
	file.close();
	int i = system("dot -Tpng -o out.png dump.dat");
	int j = system("eog out.png");
	i+=j;
}

void FSMFactory::printAndGo(Edge* edge, std::fstream& file)
{
	static std::set<char> listOfProcessedEdges;
	
	if(edge->next_.empty() || listOfProcessedEdges.find(edge->valid_) != listOfProcessedEdges.end()) return;

	for(std::map<char,Edge*>::iterator it=edge->next_.begin();
	    it != edge->next_.end();
	    it++)
	{
		file << edge->valid_ << " -> ";
		file << it->first << " [label=" << it->first << " ]\n";
		listOfProcessedEdges.insert(edge->valid_);
	}

	for(std::map<char,Edge*>::iterator it=edge->next_.begin();
	    it != edge->next_.end();
	    it++)
	{
		printAndGo(it->second,file);
	}	
}
